package module.common.net;

import com.google.gson.JsonParseException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.functions.Function;
import library.common.util.LogUtils;
import library.net.retrofit.RxSchedulers;
import library.net.retrofit.exception.RxException;
import library.net.retrofit.exception.RxExceptionHandler;

/**
 * @author Created by qiang.hou on 2018/12/11.
 * @version 1.0
 */
public class Schedulers extends RxSchedulers {
    /**
     * from RxBaseResponse<T> to T, deal error
     *
     * @param <T> data
     * @return ObservableTransformer
     */
    public static <T> ObservableTransformer<Response<T>, T> response_data2() {
        return new ObservableTransformer<Response<T>, T>() {
            @Override
            public ObservableSource<T> apply(Observable<Response<T>> upstream) {
                return upstream.map(new Function<Response<T>, T>() {

                    @Override
                    public T apply(Response<T> response) {
                        if (null == response) {
                            LogUtils.e("response_data response data error......");
                            throw new JsonParseException("response data error......");
                        }

                        if (response.isSuccess()) {
                            if (null == response.getData()) {
                                LogUtils.e("response_data response data error......");
                                throw new JsonParseException("response data error......");
                            }
                        } else {
                            throw new RxException(response.getCode(), response.getMessage());
                        }

                        return response.getData();
                    }
                }).onErrorResumeNext(new Function<Throwable, Observable<T>>() {
                    @Override
                    public Observable<T> apply(Throwable throwable) {
                        return Observable.error(RxExceptionHandler.handleException(throwable));
                    }
                });
            }
        };
    }
}
